package org.example.wc;

import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.api.java.functions.KeySelector;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.KeyedStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.util.Collector;

/**
 * DataStream实现wordcount读取文件（有界流）
 */
public class WordCountStreamDemo {
    public static void main(String[] args) throws Exception {
        //1.创建执行环境
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        //2。读取数据 
        DataStreamSource<String> lineDS = env.readTextFile(WordCountStreamDemo.class.getResource("/word.txt").getFile());
        //3。处理数据 :切分、转投、分组、聚合
        SingleOutputStreamOperator<Tuple2<String, Integer>> wordAndOneDS = lineDS.flatMap(new FlatMapFunction<String, Tuple2<String, Integer>>() {

            @Override
            public void flatMap(String value, Collector<Tuple2<String, Integer>> collector) throws Exception {
                //按照 空格 切分
                String[] words = value.split(" ");
                for (String word : words) {
                    //转投成 二元组 （word,1）
                    Tuple2<String, Integer> wordsAndOne = Tuple2.of(word, 1);
                    //通过采集器向下游发送数据
                    collector.collect(wordsAndOne);
                }
            }
        });
        //3.2分组
        KeyedStream<Tuple2<String, Integer>, Object> wordAndOneKS = wordAndOneDS.keyBy(
                new KeySelector<Tuple2<String,Integer>,Object>(){
                    @Override
                    public String getKey(Tuple2<String, Integer> value) throws Exception {
                        return value.f0;
                    }
                }
        );
        //3.3聚合
        SingleOutputStreamOperator<Tuple2<String, Integer>> sum = wordAndOneKS.sum(1);
        //4。输出数据
        sum.print();
        //5。执行：类似sparkstreaming 最后ssc.start()
        env.execute();
    }
}
